#!/usr/bin/python3

# SPDX-FileCopyrightText: Red Hat, Inc.
# SPDX-License-Identifier: GPL-2.0-or-later

"""
Parse repoStats log lines and calculate statistics.

Usage: repostat vdsm.log [...]
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import fileinput
import re
import six

pattern = re.compile(r' FINISH repoStats return=(\{.+\}\}) from=internal')

stats = {}


def liststat(a):
    b = sorted(a)
    return sum(b) / len(b),  b[0], b[-1]


for line in fileinput.input():
    match = pattern.search(line)
    if not match:
        continue
    response = eval(match.group(1))
    for uuid, info in response.items():
        stats.setdefault(uuid, {'delays': [], 'checks': []})
        stats[uuid]['delays'].append(float(info['delay']))
        stats[uuid]['checks'].append(float(info['lastCheck']))

for uuid, info in six.iteritems(stats):
    print('domain:', uuid)
    print('  delay      avg: %f min: %f max: %f' % liststat(info['delays']))
    print('  last check avg: %f min: %f max: %f' % liststat(info['checks']))
